package common

import java.sql.Connection
import java.util.Properties

import com.mchange.v2.c3p0.ComboPooledDataSource

/**
  *
  * @author Abyss
  * @date 2019/9/3
  * @description
  * 由于使用的是mysql数据库和c3p0连接池，所以提交应用时需要添加mysql连接的jar包和c3p0的jar包，在Spark-submit中添加参数
  *
  * --jars /usr/local/spark1.3/lib/mysql-connector-java-5.1.38-bin.jar,/usr/local/spark1.3/lib/c3p0-0.9.1.2.jar
  * 提交应用时添加c3p0的配置文件,在Spark-submit中添加参数
  *
  * --files /usr/local/spark1.3/conf/c3p0.properties
  */
class MySqlManager(url:String, user:String, pwd:String) extends Serializable {
  private val cpds: ComboPooledDataSource = new ComboPooledDataSource(true)
  private val prop = new Properties()
//  private var in: InputStream = _
//  isLocal match {
//    case true => in = getClass().getResourceAsStream("/c3p0.properties")
//    case false => in = new FileInputStream(new File(SparkFiles.get("c3p0.properties")))
//  }
  try {
//    prop.load(in)
    cpds.setJdbcUrl(url)
    cpds.setUser(user)
    cpds.setPassword(pwd)
    cpds.setDriverClass("com.mysql.jdbc.Driver")
    cpds.setMaxPoolSize(20)
    cpds.setMinPoolSize(5)
    cpds.setAcquireIncrement(5)
    cpds.setInitialPoolSize(10)
    cpds.setMaxIdleTime(25000)
    cpds.setIdleConnectionTestPeriod(1200)
  } catch {
    case ex: Exception => ex.printStackTrace()
  }

  def getDataSource: ComboPooledDataSource={
      return cpds
  }
  def getConnection: Connection = {
    try {
      return cpds.getConnection()
    } catch {
      case ex: Exception => ex.printStackTrace()
        null
    }
  }
}

object MySqlManager {
  var mdbManager: MySqlManager = _

  def getMDBManager(url:String, user:String, pwd:String): MySqlManager = {
    synchronized {
      if (mdbManager == null) {
        mdbManager = new MySqlManager(url,user,pwd)
      }
    }
    mdbManager
  }
}

